import {createRouter, createWebHistory} from 'vue-router'
import IndexView from "../views/IndexView.vue";
import Token from '../api/token.js'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'Home',
            component: IndexView
        },

        {
            path: '/login',
            name: 'login',
            component: () => import('../views/LoginView.vue')
        },
        {
            path: '/menuView',
            name: 'menu',
            component: () => import('../views/MenuView.vue')
        },
        {
            path: '/funcView',
            name: 'func',
            component: () => import('../views/FuncView.vue')
        },
        {
            path: '/departView',
            name: 'depart',
            component: () => import('../views/DepartView.vue')
        },
        {
            path: '/positionView',
            name: 'position',
            component: () => import('../views/PositionView.vue')
        },
        {
            path: '/roleView',
            name: 'role',
            component: () => import('../views/RoleView.vue')
        },
        {
            path: '/userView',
            name: 'user',
            component: () => import('../views/UserView.vue')
        },
        {
            path: '/logServiceView',
            name: 'service',
            component: () => import('../views/ServerLogView.vue')
        },
        {
            path: '/loginLogView',
            name: 'loginLog',
            component: () => import('../views/LoginLogView.vue')
        },
        {
            path: '/logout',
            name: 'logout',
            component: () => import('../views/Logout.vue')
        },
    ]
})


// 绑定 全局 路由守卫， 用来 拦截 没有登录的请求，必须 先登录才能访问
router.beforeEach((to, from, next) => {
    // to : 去哪里
    // from : 从哪里来
    // next : 是一个函数 ,next(false) 阻止访问，  next() : 允许访问， next('/path') : 跳转到指定路径
    if (to.name == "login") {
        next();
        return;
    }
    // 判断状态管理中的 user是否有值
    if (Token.getCurrentUser() != null) {
        next();
        return;
    }

    // 如果 不是登录 请求，那么 判断用户是否登录
    Token.getAccessToken().then(token => {
        // 根据令牌 获取当前登录的用户信息
        Token.setCurrentUserAndAuthorities(token);
        next();
    }).catch(error => {
        next({name: "login"})
    })
})


export default router
